<template>
  <div class="wrapper">
    <el-row style="padding-top: 10px;width: 98%">
      <el-col :span="24">
        <el-card v-if="loading" shadow="hover" class="project-card">
          <div class="loading">加载中...</div>
        </el-card>
        <el-card v-else-if="state.paySatsus === 0" shadow="hover" class="project-card">
          <template #header>
            <div class="card-header">
              <span class="amount">¥ {{ state.orderInfo.orderAmount }}</span>
            </div>
          </template>
          <div class="project-info">
            <div class="info-item" v-for="(value, label) in orderDetails" :key="label">
              <span class="label">{{ label }}：</span>
              <span class="value">{{ value }}</span>
            </div>
          </div>
          <el-button type="primary" class="pay-button" @click="pay">立即支付</el-button>
        </el-card>
        <el-card v-else-if="state.paySatsus === 1" shadow="hover" class="project-card">
          <el-result
              icon="success"
              title="已经支付，无需支付！"
              sub-title="有疑问联系客服！将为您全程服务!"
          >
            <template #extra>
              <el-image src="https://xunyingcloud.cn/_nuxt/kefu.DY2rjQmw.png"/>
              <el-button round @click="navigateTo('/')">了解更多</el-button>
            </template>
          </el-result>
        </el-card>
        <el-card v-else-if="state.paySatsus === 2" shadow="hover" class="project-card">
          <el-result
              icon="error"
              title="订单不存在！"
              sub-title="有疑问联系客服！将为您全程服务!"
          >
            <template #extra>
              <el-image src="https://xunyingcloud.cn/_nuxt/kefu.DY2rjQmw.png"/>
              <el-button round @click="navigateTo('/')">了解更多</el-button>
            </template>
          </el-result>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import {useRoute} from 'vue-router';
import requester from "~/utils/request";
import {useHead} from "#app";
import {ref, reactive, onMounted, watch} from 'vue';

useHead({
  title: '订单支付 - 迅颖',
  script: [
    {
      src: 'http://res2.wx.qq.com/open/js/jweixin-1.6.0.js',
      type: 'text/javascript',
    },
  ]
});
let intervalId: number | null = null;
const route = useRoute();
let orderNo = route.query.orderNo;
//获取公众号code值交给后端
const code = route.query.code;
const state = reactive({
  orderInfo: {} as any,
  paySatsus: 5,
});
const loading = ref(true); // 添加加载状态
const orderDetails = ref({}); // 用于存储订单信息

// 监听 paySatsus 的变化
watch(() => state.paySatsus, (newValue) => {
  if (newValue === 1) {
    stopPolling();
  }
});
const pay = () => {
  if (state.orderInfo.sendType == 0) {
    h5Pay(state.orderInfo.sendType)
  } else if (state.orderInfo.sendType == 1) {
    //有值获取编号,使用code换取openId
    wxPay(state.orderInfo.sendType, code)
  } else {
    ElMessage.error("查询不到支付类型，请联系客服处理！");
  }
};

/**
 * H5支付
 */
function h5Pay(sendType: number) {
  requester.post("/api/project/h5/pay", {
    "orderNo": state.orderInfo.orderNo,
    "amount": state.orderInfo.orderAmount,
    "sendType": sendType,
  }).then((response: any) => {
    if (state.orderInfo.sendType == 0) {
      if (response.data && response.data.payUrl) {
        window.location.href = response.data.payUrl;
      } else {
        ElMessage.error("支付链接无效");
      }
    }
  }).catch((error) => {
    ElMessage.error("支付请求失败，请稍后重试");
    console.error(error);
  });
}

/**
 * 公众号支付支付
 */
function wxPay(sendType: number, code: any) {
  requester.post("/api/project/h5/pay", {
    "orderNo": state.orderInfo.orderNo,
    "amount": state.orderInfo.orderAmount,
    "sendType": sendType,
    "code": code,
  }).then((response: any) => {
    // 调起微信JSAPI支付
    bootWechatJSAPIPay(response.data.jsonObject);
  }).catch((error) => {
    ElMessage.error("支付请求失败，请稍后重试");
    console.error(error);
  });
}

/**
 * @description: 通过JSAPI下单API成功获取预支付交易会话标识（prepay_id）后，需要通过JSAPI调起支付API来调起微信支付收银台
 * 注1：WeixinJSBridge内置对象在其他浏览器中无效
 * 注2：此API需要将请求参数进行签名（参与签名的参数为：appId、timeStamp、nonceStr、package，参数区分大小写）
 * @param {*}
 * @return {*}
 */
function onBridgeReady(res: any) {
  /* eslint-disable-next-line */
  WeixinJSBridge.invoke('getBrandWCPayRequest', {
        // 公众号ID，由商户传入
        'appId': res.appId,
        // 时间戳（转为String类型，兼容IOS “未传timeStamp”问题）
        'timeStamp': String(res.timeStamp),
        // 随机串
        'nonceStr': res.nonceStr,
        // 预支付交易会话标识
        'package': res.package,
        // 微信签名方式
        'signType': res.signType,
        // 微信签名
        'paySign': res.paySign
      },
      function (result: any) {
        // 微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        // 支付成功
        if (result.err_msg === 'get_brand_wcpay_request:ok') {
          console.log('支付成功');
        }
        // 支付取消
        if (result.err_msg === 'get_brand_wcpay_request:cancel') {
          console.log('支付取消');
        }
        // 支付失败
        if (result.err_msg === 'get_brand_wcpay_request:fail') {
          console.log('支付失败');
        }
      });
}
/**
 * @description: 调起微信JSAPI支付
 * @param {*}
 * @return {*}
 */
function bootWechatJSAPIPay(res: any) {
  let document: any;
  if (typeof WeixinJSBridge === 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
    }
  } else {
    onBridgeReady(res);
  }
}

onMounted(async () => {
  loading.value = true; // 开始加载
  await Promise.all([getOrderInfo(), startPolling(), patStatus()]); // 并行调用
});

/**
 * 获取订单详情
 */
async function getOrderInfo() {
  try {
    //获取订单详情
    if (orderNo === undefined) {
      orderNo = route.query.state
    }
    const response = await requester.post("/api/project/order", {"orderNo": orderNo});
    //如果订单是公众号订单获取公众号参数
    if (response.data.sendType) {
      //没有code才去获取值
      if (!code) {
        getCode(route.query.orderNo)
      }
    }
    //保存订单详情
    state.orderInfo = response.data;
    orderDetails.value = {
      "项目编号": state.orderInfo.orderNo,
      "项目名称": state.orderInfo.projectName,
      "交付日期": state.orderInfo.deliveryTime,
      "订单名称": state.orderInfo.orderName,
    };
  } catch (error) {
    console.error("获取订单信息失败", error);
  } finally {
    loading.value = false; // 数据加载完成
  }
}

// 开始轮询
async function startPolling() {
  intervalId = setInterval(patStatus, 2000); // 定时请求
}

// 停止轮询
function stopPolling() {
  if (intervalId !== null) {
    clearInterval(intervalId);
    intervalId = null;
  }
}

/**
 * 获取微信公众号code
 */
function getCode(orderNo: any) {
  //拼接链接进行登录
  window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4754a2bb841ba595&redirect_uri=` +
      encodeURIComponent("https://xunyingcloud.cn/my/mobile/order") +
      `&response_type=code&scope=snsapi_base&state=${orderNo}&connect_redirect=1#wechat_redirect`)
}

/**
 * 获取支付状态
 */
async function patStatus() {
  try {
    const response: any = await requester.get(`/api/project/getOrder?orderNo=${orderNo}`);
    if (response.code === 300) {
      ElMessage.error(response.msg);
      return;
    }
    if (response.data) {
      state.paySatsus = 1;
    } else {
      state.paySatsus = 0;
    }
  } catch (error) {
    console.error("获取支付状态失败", error);
  }
}
</script>
<style scoped lang="scss">
.wrapper {
  width: 100%;
  height: 100vh;
  background-color: #f4f4f4;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 5px;
}

.project-card {
  width: 100%;
  max-width: 600px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.loading {
  text-align: center;
  font-size: 18px;
  color: #666;
}

.card-header {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
  display: inline-block;
}

.project-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;

  .label {
    font-weight: bold;
    color: #333;
  }

  .value {
    color: #666;
  }
}

.pay-button {
  width: 100%;
  margin-top: 20px;
  font-size: 18px;
}
</style>
